package cn.iocoder.yudao.module.erp.service.marketcontract;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.order.ErpPurchaseOrderSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.marketcontract.MarketContractProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpPurchaseOrderItemDO;
import cn.iocoder.yudao.module.erp.dal.mysql.marketcontract.MarketContractProductMapper;
import cn.iocoder.yudao.module.erp.service.product.ErpProductService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.erp.controller.admin.marketcontract.vo.*;
import cn.iocoder.yudao.module.erp.dal.dataobject.marketcontract.ErpMarketContractDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.erp.dal.mysql.marketcontract.ErpMarketContractMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;

/**
 * 市场管理合同信息 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpMarketContractServiceImpl implements ErpMarketContractService {

    @Resource
    private ErpMarketContractMapper marketContractMapper;
    @Resource
    private ErpProductService productService;
    @Resource
    private MarketContractProductMapper marketContractProductMapper;

    @Override
    public Long createMarketContract(ErpMarketContractSaveReqVO createReqVO) {
        List<MarketContractProductDO> marketContractProductDOS = validateItems(createReqVO.getItems());
        // 插入
        ErpMarketContractDO marketContract = BeanUtils.toBean(createReqVO, ErpMarketContractDO.class);
        marketContractMapper.insert(marketContract);

        marketContractProductDOS.forEach(o -> o.setContractId(marketContract.getId()));
        marketContractProductMapper.insertBatch(marketContractProductDOS);
        // 返回
        return marketContract.getId();
    }

    @Override
    public void updateMarketContract(ErpMarketContractSaveReqVO updateReqVO) {
        // 校验存在
        validateMarketContractExists(updateReqVO.getId());

        List<MarketContractProductDO> marketContractProductDOS = validateItems(updateReqVO.getItems());

        // 更新
        ErpMarketContractDO updateObj = BeanUtils.toBean(updateReqVO, ErpMarketContractDO.class);
        marketContractMapper.updateById(updateObj);

        updateItems(updateReqVO.getId(), marketContractProductDOS);
    }


    private List<MarketContractProductDO> validateItems(List<ErpMarketContractSaveReqVO.ProductItem> list) {
        // 1. 校验产品存在
        List<ErpProductDO> productList = productService.validProductList(
                convertSet(list, ErpMarketContractSaveReqVO.ProductItem::getProductId));
        Map<Long, ErpProductDO> productMap = convertMap(productList, ErpProductDO::getId);
        // 2. 转化为 ErpPurchaseOrderItemDO 列表
        return convertList(list, o -> BeanUtils.toBean(o, MarketContractProductDO.class, item -> {
            item.setProductUnitId(productMap.get(item.getProductId()).getUnitId());
            item.setProductTypeId(productMap.get(item.getProductId()).getCategoryId());
        }));
    }

    private void updateItems(Long id, List<MarketContractProductDO> newList) {
        // 第一步，对比新老数据，获得添加、修改、删除的列表
        List<MarketContractProductDO> oldList = marketContractProductMapper.selectList(new QueryWrapper<MarketContractProductDO>().eq("contract_id", id));
        List<List<MarketContractProductDO>> diffList = diffList(oldList, newList, // id 不同，就认为是不同的记录
                (oldVal, newVal) -> oldVal.getId().equals(newVal.getId()));

        // 第二步，批量添加、修改、删除
        if (CollUtil.isNotEmpty(diffList.get(0))) {
            diffList.get(0).forEach(o -> o.setContractId(id));
            marketContractProductMapper.insertBatch(diffList.get(0));
        }
        if (CollUtil.isNotEmpty(diffList.get(1))) {
            marketContractProductMapper.updateBatch(diffList.get(1));
        }
        if (CollUtil.isNotEmpty(diffList.get(2))) {
            marketContractProductMapper.deleteBatchIds(convertList(diffList.get(2), MarketContractProductDO::getId));
        }
    }



    @Override
    public void deleteMarketContract(Long id) {
        // 校验存在
        validateMarketContractExists(id);
        // 删除
        marketContractMapper.deleteById(id);
    }

    @Override
        public void deleteMarketContractListByIds(List<Long> ids) {
        // 校验存在
        validateMarketContractExists(ids);
        // 删除
        marketContractMapper.deleteByIds(ids);
        }

    private void validateMarketContractExists(List<Long> ids) {
        List<ErpMarketContractDO> list = marketContractMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(MARKET_CONTRACT_NOT_EXISTS);
        }
    }

    private void validateMarketContractExists(Long id) {
        if (marketContractMapper.selectById(id) == null) {
            throw exception(MARKET_CONTRACT_NOT_EXISTS);
        }
    }

    @Override
    public ErpMarketContractDO getMarketContract(Long id) {
        return marketContractMapper.selectById(id);
    }

    @Override
    public PageResult<ErpMarketContractDO> getMarketContractPage(ErpMarketContractPageReqVO pageReqVO) {
        return marketContractMapper.selectPage(pageReqVO);
    }

    @Override
    public List<MarketContractProductDO> getMarketContractItemsByContractId(Long contractId) {
        return marketContractProductMapper.selectList(new QueryWrapper<MarketContractProductDO>().eq("contract_id", contractId));
    }

}
